<template>
  <Transition name="back-to-top-fade">
    <AxiomButton
      v-if="visible"
      class="axiom-back-to-top"
      @click="scrollToTop"
      :title="tooltip"
      icon="ArrowUp"
      circle
    />
  </Transition>
</template>

<script>
import AxiomButton from './AxiomButton.vue';
// // import { GlobalUtilsMixin } from '@/utils/globalUtils';

export default {
  name: 'AxiomBackToTop',
  // // mixins: [GlobalUtilsMixin],
  components: {
    AxiomButton,
  },
  props: {
    // 显示阈值（滚动距离超过此值时显示按钮）
    threshold: {
      type: Number,
      default: 300
    },
    // 提示文本
    tooltip: {
      type: String,
      default: '回到顶部'
    },
    // 滚动行为
    behavior: {
      type: String,
      default: 'smooth', // 'smooth' | 'auto'
      validator: value => ['smooth', 'auto'].includes(value)
    },
    // 滚动目标的选择器
    target: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      scrollTarget: null,
      throttledScrollHandler: null
    };
  },
  methods: {
    // 滚动到顶部
    scrollToTop() {
      // this.$logger.debug('触发回到顶部操作');
      // 优先滚动内容区域
      const targetElement = this.scrollTarget || window;
      
      targetElement.scrollTo({
        top: 0,
        behavior: this.behavior
      });
    },

    // 检查滚动位置
    checkScrollPosition() {
      // 优先检查主要滚动容器
      const targetElement = this.scrollTarget;
      let scrollTop = 0;
      
      if (targetElement && targetElement !== window) {
        // 内容区域滚动
        scrollTop = targetElement.scrollTop;
      } else {
        // 回退到页面级滚动
        scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      }
      
      this.visible = scrollTop > this.threshold;
    },

    // 节流函数
    throttle(fn, delay) {
      let timeoutId = null;
      let lastExecTime = 0;
      
      const throttledFn = (...args) => {
        const currentTime = Date.now();
        if (currentTime - lastExecTime > delay) {
          fn.apply(this, args);
          lastExecTime = currentTime;
        } else {
          if (timeoutId) {
            clearTimeout(timeoutId);
          }
          timeoutId = setTimeout(() => {
            fn.apply(this, args);
            lastExecTime = Date.now();
            timeoutId = null;
          }, delay - (currentTime - lastExecTime));
        }
      };
      
      throttledFn.cancel = () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
      };
      
      return throttledFn;
    }
  },
  mounted() {
    this.throttledScrollHandler = this.throttle(this.checkScrollPosition, 100);

    if (this.target) {
      this.scrollTarget = document.querySelector(this.target);
      if (!this.scrollTarget) {
        // this.$logger.warn(`未找到滚动目标: ${this.target}，将回退到 window`);
      }
    }

    const effectiveTarget = this.scrollTarget || window;

    // 监听滚动事件
    effectiveTarget.addEventListener('scroll', this.throttledScrollHandler, { passive: true });
    
    // 初始检查
    this.checkScrollPosition();
  },
  unmounted() {
    // 取消节流定时器
    if (this.throttledScrollHandler && this.throttledScrollHandler.cancel) {
      this.throttledScrollHandler.cancel();
    }
    
    const effectiveTarget = this.scrollTarget || window;
    // 移除滚动监听
    effectiveTarget.removeEventListener('scroll', this.throttledScrollHandler);
  }
};
</script>

<style lang="scss">
@use '../../styles/components/common/axiom-back-to-top';
</style>

 